package com.roadmap.struts.filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.roadmap.struts.action.ActionConst;

/** This class is used to filter those unauthorized accesses. */
public class AccessControlFilter extends HttpServlet implements Filter {
	private static final long serialVersionUID = 8445122977255428041L;
	// private final Logger logger =
	// Logger.getLogger(AccessControlFilter.class);
	private String _onFailure = ActionConst.LOGON_SERVLET;
	// private FilterConfig filterConfig;

	// URLs stored in this Set should not be filtered
	private final static Set<String> unfilterredURLs = new HashSet<String>();
	static {
		unfilterredURLs.add("/logon.do");
		unfilterredURLs.add("/signf.do");
		unfilterredURLs.add("/signs.do");
		unfilterredURLs.add("/getpwd.do");
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		// this.filterConfig = filterConfig;

		String page = filterConfig.getInitParameter("failPage");
		if (page != null) {
			this._onFailure = page;
		}
	}

	public void doFilter(ServletRequest sRequest, ServletResponse sResponse,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) sRequest;
		HttpServletResponse response = (HttpServletResponse) sResponse;

		// when the request URL is authorized and the user doesn't log on yet
		if (!unfilterredURLs.contains(request.getServletPath())
				&& !isLoggedOn(request) && !request.getServletPath().equals(_onFailure)) {
			response.sendRedirect(request.getContextPath()
					+ ActionConst.LOGON_SERVLET);
		}

		filterChain.doFilter(request, response);
	}

	public void destroy() {

	}

	private boolean isLoggedOn(HttpServletRequest request) {
		String aspirantId = (String) request.getSession().getAttribute(
				ActionConst.Aspirant_Id_In_Session);
		if (aspirantId != null && aspirantId.trim().length() != 0) {
			return true;
		}
		return false;
	}

}
